package com.Glow.reggie.controller;

import com.Glow.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author Glow
 * @Date 2022-07-31 23:27:29
 * @Description 文件上传和下载
 * @Version 1.0
 */
@RestController
@RequestMapping("common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;


    @RequestMapping("upload")
    //上传文件可以省略RequestBody
    public R<String> upload(MultipartFile file)
    {
        //file是一个临时缓存文件，如果没转存成功将会自动清楚缓存，想测试就在LoginCheckFilter那里添加放行路径
       log.info("上传的文件信息：{}",file.toString());
     //获取原始文件名
        String OriginalFileName = file.getOriginalFilename();
        //讲文件名截取
        String suffix = OriginalFileName.substring(OriginalFileName.lastIndexOf("."));
       //使用UUID生成文件名防止文件重复造成文件覆盖
        String fileName = UUID.randomUUID().toString()+suffix;
        //创建目录，如果不存在该文件夹的话
        File checkdir = new File(basePath);
        if(!checkdir.exists())
        {
            checkdir.mkdir();
        }
            try{
           //将file临时文件转移到指定位置
            file.transferTo(new File(basePath+fileName));
       }catch (IOException e)
       {

       }
       return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     * @return
     */
    @RequestMapping("download")
    @GetMapping
    //下载转存缓存文件
    public R<String> download(String name, HttpServletResponse response)
    {
        try {
            FileInputStream inputStream = new FileInputStream(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte[] bytes = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(bytes)) != -1)
            {
                outputStream.write(bytes,0,length);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
        }catch (Exception e)
        {
            e.printStackTrace();
        }

        return  null;
    }
}
